package com.why.blog.Interceptor;

import com.why.blog.bean.User;
import com.why.blog.service.userService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @program: blog
 * @description:
 * @author: @why
 * @create: 2021-01-19 12:01
 **/
@Component
@Slf4j
public class loginInterceptor implements HandlerInterceptor {
    @Autowired
    userService user;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getSession().getAttribute("user") != null) {
            return true;
        }
       // log.error("拦截开始");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if(!StringUtils.hasLength(username)||!StringUtils.hasLength(password)){
            response.sendRedirect("/admin/login");
            return false;
        }
        User user = this.user.getUser();
        if (!username.equals(user.getName())) {
            HttpSession session = request.getSession();
            session.setAttribute("error", "用户名错误，请检查！");
            session.setMaxInactiveInterval(6);
            response.sendRedirect("/admin/login");
            return false;
        } else if (!password.equals(user.getPassword())) {
            HttpSession session = request.getSession();
            session.setAttribute("error", "密码错误，请检查！");
            session.setMaxInactiveInterval(6);
            response.sendRedirect("/admin/login");
            return false;
        } else {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            session.setMaxInactiveInterval(360000);
            response.sendRedirect("/admin/dashboard");
            return true;
        }


    }

}